package com.zhaoyue.study.concurrency.thread.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: zhaoyue
 * Date: 2016/8/31
 * Time: 14:16
 * ThreadLocal 线程本地变量
 */
public class SafeTask implements Runnable {

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    private ThreadLocal<Date> startDate = new ThreadLocal<Date>(){
        @Override
        protected Date initialValue() {
            return new Date();
        }
    };



    public void run() {
        System.out.printf("Starting Thread: %s : %s\n",Thread. currentThread().getId(),format.format(startDate.get()));
        try{
            TimeUnit.SECONDS.sleep((int)Math.rint(Math.random()*50));
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.printf("Thread Finished: %s : %s\n",Thread. currentThread().getId(),format.format(startDate.get()));
    }

    public static void main(String[] args) throws Exception{
        SafeTask safeTask = new SafeTask();
        for(int i=0;i<10;i++){
            Thread thread = new Thread(safeTask);
            thread.start();
            TimeUnit.SECONDS.sleep(1);
        }
    }
}
